package com.wlyuan.open.scanner.utils;

import com.wlyuan.mybatis.utils.BatchHandlerUtil;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;

/**
 * @author lijing
 * @description
 */
public class BatchSelectUtils {

    /**
     * 批量保护数量
     */
    private static final Integer OPEN_BATCH_PROTECT = 1000;

    /**
     * 批次数量
     */
    private static final Integer NUMBER_BATCH_PROTECT = 1000;

    /**
     * 批量分批查询
     *
     * @param list  原数据量
     * @param batch 保护方法
     * @param <T>   处理类型
     * @param <R>   返回类型
     * @return 汇总数据
     */
    public static <T, R> List<R> batch(List<T> list, Function<List<T>, List<R>> batch) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        if (list.size() > OPEN_BATCH_PROTECT) {
            ArrayList<R> end = new ArrayList<>();
            for (int i = 0; i < list.size(); i += NUMBER_BATCH_PROTECT) {
                int lastIndex = Math.min(i + NUMBER_BATCH_PROTECT, list.size());
                end.addAll(batch.apply(list.subList(i, lastIndex)));
            }
            return end;
        } else {
            return batch.apply(list);
        }
    }


    public static <M, T> void batchHandler(SqlSessionFactory sqlSessionFactory,
                                           List<T> list, Class<M> clazz, BiConsumer<M, T> biConsumer) {
        BatchHandlerUtil.batchHandler(sqlSessionFactory, list, clazz, biConsumer);
        SqlSessionUtils.getSqlSession(sqlSessionFactory).clearCache();
    }
}
